<template>
  <div class="card content-box" v-loading="loading" element-loading-text="加载中...">
    <div v-if="error" class="error-container">
      <el-alert :title="error" type="error" :closable="false" />
    </div>
    <iframe v-else :src="src" frameborder="0" class="full-iframe" @load="handleIframeLoad" @error="handleIframeError"></iframe>
  </div>
</template>

<script setup lang="ts">
import { ref, watchEffect, onMounted, onUnmounted } from "vue";
import { ElAlert } from "element-plus";
import { GetLink } from "@/api/modules/upload";

interface Props {
  name?: { path: string };
  link: string;
}

const props = withDefaults(defineProps<Props>(), {
  name: () => ({ path: "" }),
  link: ""
});

const src = ref<any>("");
const loading = ref(true);
const error = ref<string | null>(null);

const fetchLink = async () => {
  if (props.link) {
    src.value = props.link;
  } else {
    try {
      const res = await GetLink(props.name);
      src.value = res.data;
    } catch (err) {
      error.value = "获取链接失败，请稍后重试";
      console.error("Error fetching link:", err);
    } finally {
      loading.value = false;
    }
  }
};

const handleIframeLoad = () => {
  loading.value = false;
};

const handleIframeError = () => {
  error.value = "加载文档失败，请检查链接是否有效";
  loading.value = false;
};

let stopWatchEffect: (() => void) | null = null;

onMounted(() => {
  stopWatchEffect = watchEffect(fetchLink);
});

onUnmounted(() => {
  if (stopWatchEffect) {
    stopWatchEffect();
  }
});
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
